﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.Net;
using HtmlAgilityPack;
using System.Reflection;
using System.Data.SqlServerCe;
using System.Collections;
using System.Threading;
using System.Net.Configuration;
using System.Diagnostics;

namespace WBrowser
{
    public partial class Links : Form
    {
        private WBrowsers _parentForm;
        private DataTable _dbForums; //use for combobox
        public List<string> _urlList = new List<string>();
        public int _selectedForums = 0;
        public int _currentPost = -1;

        /// <summary>
        /// Provide a key-value-pair collection of form elements 
        /// </summary>
        public FormElementCollection FormElements { get; set; }

        public Links()
        {
            InitializeComponent();

            //_parentForm = parent;
            MITI.BaseDBCe.g_ConnectStr = GeneralClass.ConnectString();

            //init datatable for comboboxForum
            _dbForums = new DataTable("Forum");
            _dbForums.Columns.Add("url");
            _dbForums.Columns.Add("forum_name");
            //add data
            _dbForums.Rows.Add("All", "All");
        }

        public Links(WBrowsers parent, string url)
        {
            InitializeComponent();

            _parentForm = parent;
            MITI.BaseDBCe.g_ConnectStr = GeneralClass.ConnectString();

            //init datatable for comboboxForum
            _dbForums = new DataTable("Forum");
            _dbForums.Columns.Add("url");
            _dbForums.Columns.Add("forum_name");
            //add data
            _dbForums.Rows.Add("All", "All");
        }

        #region functions

        private void AddKeyWord(int type, string key)
        {
            // TODO: This line of code loads data into the 'mpconfigDataSet.Keywords' table. You can move, or remove it, as needed.
            mpconfigDataSetTableAdapters.KeywordsTableAdapter keywordsTableAdapter = new mpconfigDataSetTableAdapters.KeywordsTableAdapter();
            keywordsTableAdapter.ClearBeforeFill = true;
            keywordsTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
            keywordsTableAdapter.Fill(this.mpconfigDataSet.Keywords);
            
            //Add a new keyword
            BindingSource keywordsBindingSource = new BindingSource(mpconfigDataSet, "keywords");
            keywordsBindingSource.Filter = "KeyType = " + type.ToString() + " and KeyName = '" + key.Trim().ToLower().ToString() + "'"; 
            if (keywordsBindingSource.Count == 0)
            {
                DataRow dr = mpconfigDataSet.Keywords.NewRow();
                dr["KeyType"] = type;
                dr["KeyName"] = key;
                mpconfigDataSet.Keywords.Rows.Add(dr);
                keywordsTableAdapter.Update(mpconfigDataSet.Keywords);
            }
        }

        private string GetName(string url)
        {
            string pattern1 = @"(http(s|)://|)(www\.|)";
            Regex r1 = new Regex(pattern1);
            //string pattern2 = "(.com|.org|.co.uk|.net|.info)(/|).*";
            string pattern2 = "/.*";
            Regex r2 = new Regex(pattern2);
            Match m;

            string forumname = url.ToLower();
            m = r1.Match(forumname);

            //stem head
            if (m.Success)
                forumname = forumname.Replace(m.Value, "");

            //Stem tail
            m = r2.Match(forumname);
            if (m.Success)
            {
                forumname = forumname.Replace(m.Value, "");
            }
            return forumname;
        }

        private string FormatUrl(string url)
        {
            string result = url;
            string pattern = @"/\w+(\.php|\.html).*";
            //string pattern = @"(/\w+(\.php|\.html).*$|/$)";
            Regex r = new Regex(pattern);
            Match m;

            //Stem tail
            m = r.Match(url);
            //if (m.Success)
            result = m.Success ? url.Replace(m.Value, "") : result;

            pattern = @"/$";
            r = new Regex(pattern);
            m = r.Match(result);
            result = m.Success ? result.Substring(0, result.Length - 1) : result;
            return result;
        }

        #endregion

        #region Events
        #region Main

        private void Links_Load(object sender, EventArgs e)
        {
            try
            {
                // TODO: This line of code loads data into the 'mpconfigDataSet.Templates' table. You can move, or remove it, as needed.
                this.templatesTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
                this.templatesTableAdapter.Fill(this.mpconfigDataSet.Templates);

                ServicePointManager.UseNagleAlgorithm = true;
                ServicePointManager.Expect100Continue = false;
                ServicePointManager.CheckCertificateRevocationList = true;
                ServicePointManager.DefaultConnectionLimit = 200; //ServicePointManager.DefaultPersistentConnectionLimit;
                ServicePointManager.MaxServicePoints = 100;
                //ServicePointManager.MaxServicePointIdleTime = 100;
                //ServicePointManager.CertificatePolicy = new AcceptAllCertificatePolicy();
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                //ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
                
                toolStripStatusLabelComplete.Visible = false;
                toolStripProgressBar1.Visible = false;

                comboBoxForums.SelectedIndex = 0;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnGetThreads_Click(object sender, EventArgs e)
        {
            //string url;
            tabControl1.SelectTab(tabPageForumThreads);
            try
            {
                _selectedForums = 0;
                //Set biến để kiểm tra xem id có nằm trong url không
                foreach (DataGridViewRow dr in dataGridViewForums.Rows)
                {
                    if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value != null)
                    {
                        if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value == true)
                        {
                            //Check forums are loaded yet
                            var query = from row in _dbForums.AsEnumerable()
                                        where row["forum_name"].ToString() == dr.Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString()
                                        select row;
                            if (query.Count() == 0)
                            {
                                _selectedForums++;

                                //Use threads
                                HttpThread hp = new HttpThread();
                                hp.startThread_GetIdThreads(this, mpconfigDataSet.Tables["Templates"].Rows.Find(dr.Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString()));//, mpconfigDataSet.Tables["ThreadTemplates"]);

                                //Add forums in combobox
                                _dbForums.Rows.Add(dr.Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString(), dr.Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString());
                            }
                        }
                    }
                }

                comboBoxSelectForum.DataSource = _dbForums;
                comboBoxSelectForum.DisplayMember = "url";
                comboBoxSelectForum.ValueMember = "forum_name";


                toolStripProgressBar1.Visible = true;
                toolStripStatusLabelComplete.Visible = true;
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Minimum = 0;
                toolStripProgressBar1.Maximum = _selectedForums;
                toolStripProgressBar1.Step = 1;
                toolStripStatusLabelComplete.Text = "Loading...";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnUpdateForum_Click(object sender, EventArgs e)
        {
            //Before update ...
            this.toolStripStatusLabelComplete.Visible = false;
            this.toolStripProgressBar1.Visible = false;

            _urlList.Clear();
            foreach (DataGridViewRow dr in dataGridViewForums.Rows)
            {
                if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value != null)
                {
                    if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value == true)
                    {
                        dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value = false;
                        dr.Cells["htmlDataGridViewTextBoxColumn"].Value = "";
                    }
                }
            }

            

            this.templatesBindingSource.EndEdit();
            this.templatesTableAdapter.Update(this.mpconfigDataSet.Templates);
            mpconfigDataSet.AcceptChanges();
            MessageBox.Show("Update successful!");
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            int indexRow = dataGridViewForums.SelectedCells[0].RowIndex;
            Process.Start("firefox.exe", dataGridViewForums.Rows[indexRow].Cells["urlDataGridViewTextBoxColumn"].Value.ToString());
        }

        //private void btnSearchUrl_Click(object sender, EventArgs e)
        //{
        //    templatesBindingSource.Filter = "url like '%" + textBoxSearchUrl.Text + "%'";
        //}

        //private void btnUncheck_Click(object sender, EventArgs e)
        //{
        //    if (btnCheckForums.Text == "Uncheck All")
        //    {
        //        foreach (DataGridViewRow dr in dataGridViewForums.Rows)
        //            dr.Cells["select_forum"].Value = (object)false;
        //        btnCheckForums.Text = "Check All";
        //    }
        //    else
        //    {
        //        foreach (DataGridViewRow dr in dataGridViewForums.Rows)
        //            dr.Cells["select_forum"].Value = (object)true;
        //        btnCheckForums.Text = "Uncheck All";
        //    }
        //}
        #endregion

        #region TabPage1

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Are you sure add the titles into backlist", "Title", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
            {
                //Save
                foreach (DataGridViewRow dr in dataGridViewForumThreads.Rows)
                {
                    if (dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value != null)
                    {
                        if ((bool)dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value == true)
                        {
                            //add backlist title
                            AddKeyWord(2, dr.Cells["titleDataGridViewTextBoxColumnThread"].Value.ToString().Trim().ToLower());
                        }
                    }
                }
                MessageBox.Show("Finish!");
            }
        }

        private void btnGetFilter_Click(object sender, EventArgs e)
        {
            if (comboBoxSelectForum.SelectedIndex ==0)
            {
                MessageBox.Show("Select a specific forum to filter.");
                return;
            }
            //Reset old F, new F
            foreach (DataGridViewRow r in dataGridViewIdThreads.Rows)
            {
                r.Cells["newF"].Value = "";
            }

            

            //Add new F
            foreach (DataGridViewRow dr in dataGridViewForumThreads.Rows)
            {
                if (dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value != null)
                {
                    if ((bool)dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value == true)
                    {
                        foreach (DataGridViewRow r in dataGridViewIdThreads.Rows)
                        {
                            if (r.Cells["threadIdDataGridViewTextBoxColumn"].Value.ToString() == dr.Cells["threadnameDataGridViewTextBoxColumnThread"].Value.ToString())
                                r.Cells["newF"].Value = dr.Cells["threadidDataGridViewTextBoxColumnThread"].Value;
                        }
                    }
                }
            }
        }

        //private void btnGetId_Click(object sender, EventArgs e)
        //{

        //    try
        //    {
        //        string threadId;
        //        foreach (DataGridViewRow dr in dataGridViewForumThreads.Rows)
        //        {
        //            if (dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value != null)
        //            {
        //                if ((bool)dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value == true
        //                        && dr.Cells["idDataGridViewCheckBoxColumnThread"].Value.ToString() == string.Empty)
        //                {
        //                    //Find id by regex first
        //                    threadId = GetIDForumByRegex(dr.Cells["urlDataGridViewCheckBoxColumnThread"].Value.ToString(), textBoxRegrex1.Text);
        //                    //Get template header
        //                    dr.Cells["threadDataGridViewCheckBoxColumnThread"].Value = GetTemplateHeader(dr.Cells["titleDataGridViewCheckBoxColumnThread"].Value.ToString(), (int)enumLanguage.English);
        //                    if (threadId != string.Empty)
        //                    {
        //                        dr.Cells["idDataGridViewCheckBoxColumnThread"].Value = threadId;
        //                    }
        //                    else
        //                    {
        //                        //Use threads to get id threads in forums
        //                        HttpThread hp = new HttpThread();
        //                        hp.startThread_GetThreadId(this, dr.Cells["urlDataGridViewCheckBoxColumnThread"].Value.ToString());
        //                    }
        //                }
        //            }

        //        }
        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        private void btnCheckThreads_Click(object sender, EventArgs e)
        {
            if (btnCheckThreads.Text == "Uncheck All")
            {
                foreach (DataGridViewRow dr in dataGridViewForumThreads.Rows)
                    dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value = (object)false;
                btnCheckThreads.Text = "Check All";
            }
            else
            {
                foreach (DataGridViewRow dr in dataGridViewForumThreads.Rows)
                    dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value = (object)true;
                btnCheckThreads.Text = "Uncheck All";
            }
        }

        private void btnUpdateThread_Click(object sender, EventArgs e)
        {
            //Update new F into dataset
            foreach (DataGridViewRow r in dataGridViewIdThreads.Rows)
            {
                if (r.Cells["oldF"].Value != null &&
                    r.Cells["newF"].Value == null)
                {
                    r.Cells["newF"].Value = r.Cells["oldF"].Value;
                }
                mpconfigDataSet.Templates.FindByforum_name(comboBoxSelectForum.SelectedValue.ToString())[r.Cells["threadIdDataGridViewTextBoxColumn"].Value.ToString()] = r.Cells["newF"].Value.ToString();
            }
            templatesTableAdapter.Update(mpconfigDataSet.Templates);

            //Update keywords
            DataRow dr;
            foreach (DataGridViewRow r in dataGridViewForumThreads.Rows)
            {

                if (r.Cells["selectDataGridViewCheckBoxColumnThread"].Value != null)
                {
                    if ((bool)r.Cells["selectDataGridViewCheckBoxColumnThread"].Value == true)
                    {
                        //reset
                        r.Cells["selectDataGridViewCheckBoxColumnThread"].Value = false;

                        //Kiểm tra xem keyword đã có chưa. Nếu chưa thì thêm vào keyword mới trong table ThreadKeywords
                        var value = from key in mpconfigDataSet.ThreadKeywords.AsEnumerable()
                                    where key["ThreadId"].ToString() == r.Cells["threadnameDataGridViewTextBoxColumnThread"].Value.ToString()
                                    && key["Keyword"].ToString().ToLower() == r.Cells["titleDataGridViewTextBoxColumnThread"].Value.ToString().ToLower()
                                    select key;
                        if (value.Count() == 0)
                        {
                            dr = mpconfigDataSet.ThreadKeywords.NewRow();
                            dr["ThreadId"] = r.Cells["threadnameDataGridViewTextBoxColumnThread"].Value.ToString();
                            dr["Keyword"] = r.Cells["titleDataGridViewTextBoxColumnThread"].Value.ToString().ToLower();
                            dr["Language"] = 1;
                            mpconfigDataSet.ThreadKeywords.Rows.Add(dr);
                        }
                    }
                }
            }
            threadKeywordsTableAdapter.Update(mpconfigDataSet.ThreadKeywords);

            MessageBox.Show("Update successful!");
        }

        private void comboBoxSelectForum_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (comboBoxSelectForum.SelectedIndex == 0)
            {
                threadTemplatesBindingSource.RemoveFilter();
            }
            else
            {
                threadTemplatesBindingSource.Filter = "forum_name = '" + comboBoxSelectForum.SelectedValue + "'";
                //Add old F
                foreach (DataGridViewRow r in dataGridViewIdThreads.Rows)
                {
                    r.Cells["oldF"].Value = mpconfigDataSet.Templates.FindByforum_name(comboBoxSelectForum.SelectedValue.ToString())[r.Cells["threadIdDataGridViewTextBoxColumn"].Value.ToString()];
                }
            }
        }

        private void btnGetName_Click(object sender, EventArgs e)
        {
            string pattern1 = "(http://|)(www.|)";
            Regex r1 = new Regex(pattern1);
            //string pattern2 = "(.com|.org|.co.uk|.net|.info)(/|).*";
            string pattern2 = "/.*";
            Regex r2 = new Regex(pattern2);
            string url;
            Match m;
            try
            {
                //Set biến để kiểm tra xem id có nằm trong url không
                foreach (DataGridViewRow dr in dataGridViewForums.Rows)
                {
                    if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value != null)
                    {
                        if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value == true)
                        {
                            if (dr.Cells["urlDataGridViewTextBoxColumn"].Value != null)
                            {
                                if (dr.Cells["urlDataGridViewTextBoxColumn"].Value.ToString() != string.Empty)
                                {
                                    url = dr.Cells["urlDataGridViewTextBoxColumn"].Value.ToString();
                                    m = r1.Match(url);

                                    //Stem head
                                    if (m.Success)
                                        url = url.Replace(m.Value, "");

                                    //Stem tail
                                    m = r2.Match(url);
                                    if (m.Success)
                                    {
                                        url = url.Replace(m.Value, "");
                                    }

                                    dr.Cells["forumnameDataGridViewTextBoxColumn"].Value = url;
                                }
                            }
                        }
                    }
                }
                templatesBindingSource.EndEdit();
                templatesTableAdapter.Update(mpconfigDataSet.Templates);
                MessageBox.Show("Update successful!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region TabPage3

        //private void btnCheckDuplicates_Click(object sender, EventArgs e)
        //{
        //    if (btnCheckDuplicates.Text == "Check Duplicates")
        //    {
        //        string sql = "select * from Templates where name in (select t1.name from Templates t1 group by t1.name having count(t1.name) > 1)";
        //        checkForumsBindingSource.DataSource = MITI.BaseDBCe.ExecSql_DataSet(sql).Tables[0];
        //        btnCheckDuplicates.Text = "Uncheck Duplicates";
        //    }
        //    else
        //    {
        //        checkForumsBindingSource.DataSource = mpconfigDataSet.Templates;
        //        btnCheckDuplicates.Text = "Check Duplicates";
        //    }
        //}

        //private void btnOpenCheckForums_Click(object sender, EventArgs e)
        //{
        //    int indexRow = dataGridViewCheckForums.SelectedCells[0].RowIndex;
        //    Process.Start("firefox.exe", dataGridViewCheckForums.Rows[indexRow].Cells["urlDataGridViewTextBoxColumn1"].Value.ToString());
        //}

        private void dataGridViewCheckForums_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            //try
            //{
            //    textBoxSearchUrl.Text = dataGridViewCheckForums.Rows[e.RowIndex].Cells["forumname"].Value.ToString();
            //    btnSearchUrl_Click(null, null);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //}

            try
            {
                if (dataGridViewCheckForums.Rows[e.RowIndex].Cells["htmlDataGridViewTextBoxColumn1"].Value != null)
                {
                    richTextBoxSource.Text = dataGridViewCheckForums.Rows[e.RowIndex].Cells["htmlDataGridViewTextBoxColumn1"].Value.ToString();
                }

                //if (comboBoxSelectCommand.SelectedIndex != 1)//Check duplicates
                //{
                //    dataGridViewForums.FirstDisplayedScrollingRowIndex = e.RowIndex;
                //    dataGridViewForums.Rows[e.RowIndex].Selected = true;
                //}
                templatesBindingSource.RemoveFilter();
                int index = templatesBindingSource.Find("forum_name", dataGridViewCheckForums.Rows[e.RowIndex].Cells["forumnameDataGridViewTextBoxColumn1"].Value.ToString());
                if (index >= 0)
                {
                    dataGridViewForums.FirstDisplayedScrollingRowIndex = index;
                    dataGridViewForums.Rows[index].Selected = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #endregion

        #endregion

        //private void btnCheckDead_Click(object sender, EventArgs e)
        //{
        //    try
        //    {
        //        string url;
        //        //Set biến để kiểm tra xem id có nằm trong url không
        //        foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
        //        {
        //            if (dr.Cells["select_checkforum"].Value != null)
        //            {
        //                if ((bool)dr.Cells["select_checkforum"].Value == true)
        //                {
        //                    url = dr.Cells["url"].Value.ToString();
        //                    if (!_urlList.Contains(url))
        //                    {
        //                        //Use threads
        //                        HttpThread hp = new HttpThread();
        //                        hp.startThread_CheckForumContent(this, dr.Index, url);
        //                    }
        //                }
        //            }
        //        }

        //    }
        //    catch (Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //    }
        //}

        private void btnCheckStatusForums_Click(object sender, EventArgs e)
        {
            if (btnCheckStatusForums.Text == "Uncheck All")
            {
                foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                    dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value = (object)false;
                btnCheckStatusForums.Text = "Check All";
            }
            else
            {
                foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                    dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value = (object)true;
                btnCheckStatusForums.Text = "Uncheck All";
            }
        }

        private void btnUpdateCheckForums_Click(object sender, EventArgs e)
        {

        }

        private void comboBoxSelectCommand_SelectedIndexChanged(object sender, EventArgs e)
        {
            //checkForumsBindingSource.DataSource = mpconfigDataSet.Templates;
            //reset list contains url
            _urlList.Clear();
            

            foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                    dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value = (object)false;

            if (comboBoxSelectCommand.SelectedIndex == 0) //Check Content
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewCheckForums.Columns.Count; i++)
                    dataGridViewCheckForums.Columns[i].Visible = false;
                dataGridViewCheckForums.Columns["forumtypeDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["languageDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["contentDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["currentmembersDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["currentguestsDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["threadsDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["postsDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["membersDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["messageDataGridViewTextBoxColumn1"].Visible = true;
            }
            else if (comboBoxSelectCommand.SelectedIndex == 1)  //Check Login
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewCheckForums.Columns.Count; i++)
                    dataGridViewCheckForums.Columns[i].Visible = false;
                dataGridViewCheckForums.Columns["usernameDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["passwordDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["forumtypeDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["languageDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["contentDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["loginstatusDataGridViewTextBoxColumn1"].Visible = true;
            }
            else if (comboBoxSelectCommand.SelectedIndex == 2) //Update Forum Name
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewCheckForums.Columns.Count; i++)
                    dataGridViewCheckForums.Columns[i].Visible = false;
            }
            else if (comboBoxSelectCommand.SelectedIndex == 3) //Find statistics url
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewCheckForums.Columns.Count; i++)
                    dataGridViewCheckForums.Columns[i].Visible = false;
                dataGridViewCheckForums.Columns["usernameDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["myposturlDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["useridDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["languageDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["contentDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["posturlstatusDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["loginstatusDataGridViewTextBoxColumn1"].Visible = true;
            }
            else if (comboBoxSelectCommand.SelectedIndex == 4) //Update Profile
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewCheckForums.Columns.Count; i++)
                    dataGridViewCheckForums.Columns[i].Visible = false;
                dataGridViewCheckForums.Columns["usernameDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["passwordDataGridViewTextBoxColumn1"].Visible = true;
                dataGridViewCheckForums.Columns["emailDataGridViewTextBoxColumn1"].Visible = true;
            }
            else //Delete seleted forums
            {

            }
        }

        private void btnDoCheckForums_Click(object sender, EventArgs e)
        {
            if (comboBoxSelectCommand.SelectedIndex == 0) //Check Content
            {
                //reset numbers of forums
                _selectedForums = 0;
                string url;
                //Set biến để kiểm tra xem id có nằm trong url không
                foreach (DataGridViewRow dr in dataGridViewForums.Rows)
                {
                    if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value != null)
                    {
                        if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value == true)
                        {
                            url = dr.Cells["urlDataGridViewTextBoxColumn"].Value.ToString();
                            if (!_urlList.Contains(url))
                            {
                                _selectedForums++;
                                //Use threads
                                HttpThread hp = new HttpThread();
                                hp.startThread_CheckForumInformation(this, mpconfigDataSet.Tables["Templates"].Rows.Find(dr.Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString()));
                                //hp.startThread_CheckForumInformation(this, MITI.BaseDBCe.ExecSql_DataSet("select * from Templates where forum_name = '" + dr.Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString() + "'").Tables[0].Rows[0]);
                            }
                        }
                    }
                }
                toolStripProgressBar1.Visible = true;
                toolStripStatusLabelComplete.Visible = true;
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Minimum = 0;
                toolStripProgressBar1.Maximum = _selectedForums;
                toolStripProgressBar1.Step = 1;
                toolStripStatusLabelComplete.Text = "Loading...";
            }
            else if (comboBoxSelectCommand.SelectedIndex == 1) //Check Login
            {
                //reset numbers of forums
                _selectedForums = 0;
                string url;
                //Set biến để kiểm tra xem id có nằm trong url không
                foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                {
                    if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value != null)
                    {
                        if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value == true)
                        {
                            url = dr.Cells["urlDataGridViewTextBoxColumn1"].Value.ToString();
                            if (!_urlList.Contains(url))
                            {
                                _selectedForums++;
                                //Use threads
                                HttpThread hp = new HttpThread();
                                hp.startThread_CheckLogin(this, mpconfigDataSet.Tables["Templates"].Rows.Find(dr.Cells["forumnameDataGridViewTextBoxColumn1"].Value.ToString()));
                            }
                        }
                    }
                }
                toolStripProgressBar1.Visible = true;
                toolStripStatusLabelComplete.Visible = true;
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Minimum = 0;
                toolStripProgressBar1.Maximum = _selectedForums;
                toolStripProgressBar1.Step = 1;
                toolStripStatusLabelComplete.Text = "Loading...";

            }
            else if (comboBoxSelectCommand.SelectedIndex == 2) //Update forum name
            {
                string pattern1 = "(http(s|)://|)(www.|)";
                Regex r1 = new Regex(pattern1);
                //string pattern2 = "(.com|.org|.co.uk|.net|.info)(/|).*";
                string pattern2 = "/.*";
                Regex r2 = new Regex(pattern2);
                string forumname;
                Match m;
                
                try
                {
                    foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                    {
                        if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value != null)
                        {
                            if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value == true)
                            {
                                forumname = dr.Cells["urlDataGridViewTextBoxColumn1"].Value.ToString().ToLower();
                                m = r1.Match(forumname);

                                //stem head
                                if (m.Success)
                                    forumname = forumname.Replace(m.Value, "");

                                //Stem tail
                                m = r2.Match(forumname);
                                if (m.Success)
                                {
                                    forumname = forumname.Replace(m.Value, "");
                                }

                                //Checking whether the forumname is exists or not
                                if (templatesBindingSource.Find("forum_name", forumname) == -1)
                                    dr.Cells["forumnameDataGridViewTextBoxColumn1"].Value = forumname;
                            }
                        }
                    }
                    toolStripProgressBar1.Visible = false;
                    toolStripStatusLabelComplete.Visible = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }
            else if (comboBoxSelectCommand.SelectedIndex == 3) //Get statistics url
            {
                //************************************************************************//
                //* Use for vBulletin                                                    *//
                //************************************************************************//
                //reset numbers of forums
                _selectedForums = 0;
                string url;
                foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                {
                    if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value != null)
                    {
                        if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value == true)
                        {
                            //if (dr.Cells["typeDataGridViewTextBoxColumn1"].Value.ToString() == "vBulletin")
                            //{
                            url = dr.Cells["urlDataGridViewTextBoxColumn1"].Value.ToString();
                            if (!_urlList.Contains(url))
                            {
                                _selectedForums++;
                                //Use threads
                                HttpThread hp = new HttpThread();
                                hp.startThread_FindStatisticsUrl(this, mpconfigDataSet.Tables["Templates"].Rows.Find(dr.Cells["forumnameDataGridViewTextBoxColumn1"].Value.ToString()));
                            }
                            // }
                        }
                    }
                }

                toolStripProgressBar1.Visible = true;
                toolStripStatusLabelComplete.Visible = true;
                toolStripProgressBar1.Value = 0;
                toolStripProgressBar1.Minimum = 0;
                toolStripProgressBar1.Maximum = _selectedForums;
                toolStripProgressBar1.Step = 1;
                toolStripStatusLabelComplete.Text = "Loading...";
            }
            else if (comboBoxSelectCommand.SelectedIndex == 4) //Update default profile
            {
                string sql = "select * from Profile";
                DataRow row = MITI.BaseDBCe.ExecSql_DataSet(sql).Tables[0].Rows[0];
                foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                {
                    if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value == true)
                    {
                        dr.Cells["usernameDataGridViewTextBoxColumn1"].Value = row["username"];
                        dr.Cells["passwordDataGridViewTextBoxColumn1"].Value = row["password"];
                        dr.Cells["emailDataGridViewTextBoxColumn1"].Value = row["email"];
                    }
                }
            }
            else //Delete seleted forums
            {
                List<string> forums = new List<string>();
                int index;
                if (MessageBox.Show("Are you sure you want to delete these forums?", "Info", MessageBoxButtons.YesNo)
                    == System.Windows.Forms.DialogResult.Yes)
                {
                    //Set biến để kiểm tra xem id có nằm trong url không
                    foreach (DataGridViewRow dr in dataGridViewCheckForums.Rows)
                    {
                        if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value != null)
                        {
                            if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn1"].Value == true)
                            {
                                forums.Add(dr.Cells["forumnameDataGridViewTextBoxColumn1"].Value.ToString());
                            }
                        }
                    }
                    foreach (string s in forums)
                    {
                        index = checkForumsBindingSource.Find("forum_name", s);
                        if (index >= 0)
                        {
                            dataGridViewCheckForums.Rows.RemoveAt(index);
                            checkForumsBindingSource.EndEdit();
                        }
                    }
                    templatesTableAdapter.Update(mpconfigDataSet.Templates);
                    MessageBox.Show("Delete successful!");
                }
                toolStripProgressBar1.Visible = false;
                toolStripStatusLabelComplete.Visible = false;
            }
        }

        //public void UpdateProgess(DataRow pTemplateRow)
        //{
        //    checkForumsBindingSource.EndEdit();
        //    templatesTableAdapter.Update(pTemplateRow);
        //    // this is UI thread
        //    _urlList.Add(pTemplateRow["url"].ToString());
        //    _selectedForums--;

        //    toolStripProgressBar1.Step = (100 / (toolStripProgressBar1.Maximum - _selectedForums));
        //    toolStripProgressBar1.PerformStep();

        //    if (_selectedForums == 0)
        //    {
        //        toolStripStatusLabelComplete.Text = "Complete!";
        //        _selectedForums--;
        //    }
        //}

        private void dataGridViewForums_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = checkForumsBindingSource.Find("forum_name", dataGridViewForums.Rows[e.RowIndex].Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString());
                if (index >= 0)
                {
                    dataGridViewCheckForums.FirstDisplayedScrollingRowIndex = index;
                    dataGridViewCheckForums.Rows[index].Selected = true;
                }

                index = forumPostBindingSource.Find("forum_name", dataGridViewForums.Rows[e.RowIndex].Cells["forumnameDataGridViewTextBoxColumn"].Value.ToString());
                if (index >= 0)
                {
                    dataGridViewPostedForums.FirstDisplayedScrollingRowIndex = index;
                    dataGridViewPostedForums.Rows[index].Selected = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridViewForumThreads_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            //if (dataGridViewForums.Rows[e.RowIndex].Cells["html"].Value != null)
            //{
            //    richTextBoxSource.Text = dataGridViewForums.Rows[e.RowIndex].Cells["html"].Value.ToString();
            //    editorViewHTML.BodyHtml = richTextBoxSource.Text;
            //}
        }

        //private void btnDelete_Click(object sender, EventArgs e)
        //{
        //    if (MessageBox.Show("Are you sure you want to delete this forum", "Info", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes)
        //    {
        //        dataGridViewForums.Rows.Remove(dataGridViewForums.SelectedRows[0]);
        //        templatesBindingSource.EndEdit();
        //        templatesTableAdapter.Update(mpconfigDataSet.Templates);
        //        MessageBox.Show("Delete successful");
        //    }
        //}

        private void dataGridViewForumThreads_Sorted(object sender, EventArgs e)
        {

        }

        private void textBoxSearchUrl_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                    templatesBindingSource.Filter = textBoxSearch.Text;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Links_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.S)
            {
                textBoxSearch.Focus();
            }
        }

        private void btnRegister_Click(object sender, EventArgs e)
        {
            try
            {
                if (dataGridViewForums.SelectedRows.Count == 0)
                {
                    MessageBox.Show("Don't have a row selected");
                    return;
                }
                DataGridViewRow dr = dataGridViewForums.SelectedRows[0];
                string url = dr.Cells["urlDataGridViewTextBoxColumn"].Value.ToString();
                string username = dr.Cells["usernameDataGridViewTextBoxColumn"].Value.ToString();
                string password = dr.Cells["passwordDataGridViewTextBoxColumn"].Value.ToString();
                string targetFrameName = "_SELF";
                string additionalHeaders = "Content-Type: application/x-www-form-urlencoded" + Environment.NewLine;
                string month = "5", day = "10", year = "1983";
                string email = "hgtuan2003@gmail.com";
                if (dr.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().ToLower() == "vBulletin".ToLower())
                {
                    FormElements = new FormElementCollection((HtmlAgilityPack.HtmlDocument)null);
                    FormElements["s"] = "";
                    FormElements["securitytoken"] = "guest";
                    FormElements["do"] = "register";
                    FormElements["url"] = url;
                    FormElements["month"] = month;
                    FormElements["day"] = day;
                    FormElements["year"] = year;
                    FormElements["who"] = "adult";
                    FormElements["agree"] = "1";

                    url += @"/register.php?do=register";
                }
                else if (dr.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().ToLower() == "IPB".ToLower())
                {
                    FormElements = new FormElementCollection((HtmlAgilityPack.HtmlDocument)null);
                    FormElements["agree_to_terms"] = "1";
                    url += @"/index.php?app=core&module=global&section=register&coppa_user=&termsread=1&coppa_pass=1";
                }
                else if (dr.Cells["typeDataGridViewTextBoxColumn"].Value.ToString().ToLower().Contains("phpbb"))
                {
                    FormElements = new FormElementCollection((HtmlAgilityPack.HtmlDocument)null);
                    FormElements["agreed"] = "I+agree+to+these+terms";
                    FormElements["change_lang"] = "";
                    FormElements["creation_time"] = "";// "1294063116";
                    FormElements["form_token"] = "";// "8a439668165b0440840e15b2f12124417d46920a";

                    url += @"/ucp.php?mode=register";
                }

                string postData = FormElements.AssemblePostPayload();
                byte[] buff = Encoding.UTF8.GetBytes(postData.ToCharArray());

                //this._parentForm.username = username;
                //this._parentForm.password = password;
                //this._parentForm.email = email;
                this._parentForm.addNewTab();
                this._parentForm.getCurrentBrowser().Navigate(url, targetFrameName, buff, additionalHeaders);
                this._parentForm.Focus();
            }
            catch
            {
                
            }
            finally
            {
                
            }
        }

        private void btnBrowse_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.InitialDirectory = "c:\\";
            openFileDialog1.Filter = "html files (*.html)|*.html|xml files (*.xml)|*.txt|All files (*.*)|*.*";
            openFileDialog1.FilterIndex = 1;
            openFileDialog1.RestoreDirectory = true;
            
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    textBoxUrlBookmark.Text = openFileDialog1.FileName;
                    
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
                }
            }
        }

        private void btnAddTemplates_Click(object sender, EventArgs e)
        {
            DataRow newRow;
            foreach (DataGridViewRow dr in dataGridViewBookmark.Rows)
            {
                if (templatesBindingSource.Find("forum_name", dr.Cells["namebookmark"].Value.ToString()) == -1)
                {
                    newRow = mpconfigDataSet.Templates.NewRow();
                    newRow["forum_name"] = dr.Cells["namebookmark"].Value.ToString();
                    newRow["url"] = dr.Cells["urlbookmark"].Value.ToString();
                    mpconfigDataSet.Templates.Rows.Add(newRow);
                    dr.Cells["statusbookmark"].Value = "Added";
                }
                else
                    dr.Cells["statusbookmark"].Value = "Duplicate";
            }
        }

       

        private void btnRun_Click(object sender, EventArgs e)
        {
            HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();
            doc.Load(textBoxUrlBookmark.Text);
            foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))
            {
                dataGridViewBookmark.Rows.Add(GetName(node.Attributes["href"].Value.ToString()), FormatUrl(node.Attributes["href"].Value));
            }
        }

        private void dataGridViewForums_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)
        {
            //string value = dataGridViewForums.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        }

        private void dataGridViewForums_CellEndEdit(object sender, DataGridViewCellEventArgs e)
        {
            //dataGridViewForums.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            //string forumname = GetName(dataGridViewForums.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString());
            //int index = templatesBindingSource.Find("forum_name", forumname);
            //if (index >= 0)
            //{
            //    MessageBox.Show("The forum is exists");
            //}
        }

        private void btnFormatUrl_Click(object sender, EventArgs e)
        {
            //don't select empty row
            for (int i = 0; i < dataGridViewForums.Rows.Count - 1; i++ )
            {
                dataGridViewForums.Rows[i].Cells["urlDataGridViewTextBoxColumn"].Value = FormatUrl(dataGridViewForums.Rows[i].Cells["urlDataGridViewTextBoxColumn"].Value.ToString());
                //dataGridViewForums.Rows[i].Cells["myposturlDataGridViewTextBoxColumn"].Value = dataGridViewForums.Rows[i].Cells["myposturlDataGridViewTextBoxColumn"].Value.ToString().Replace("&amp;", "&");
            }
        }

        private void btnFilter_Click(object sender, EventArgs e)
        {
            //type like 'vBulletin' and language='English' and content like 'App%' and convert(current_guests,'System.Int32') > 0
            textBoxFilterCheckForums.Text = "type like 'vBulletin' and language='English' and content like 'App%' and convert(current_guests,'System.Int32') > 0";
        }

        private void textBoxFilterCheckForums_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.KeyCode == Keys.Enter)
                    checkForumsBindingSource.Filter = textBoxFilterCheckForums.Text;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnAddPost_Click(object sender, EventArgs e)
        {
            Post frm = new Post(this);
            frm.ShowDialog();
        }

        public int AddPost(string title, string content, string lang, string date)
        {
            int id = -1;
            try
            {
                mpconfigDataSet.PostsRow postRow = mpconfigDataSet.Posts.NewPostsRow();
                postRow.title = title;
                postRow.content = content;
                postRow.language = lang;
                postRow.create = date;
                mpconfigDataSet.Posts.AddPostsRow(postRow);
                postsTableAdapter.Update(mpconfigDataSet.Posts);
                postsTableAdapter.Fill(mpconfigDataSet.Posts);

                mpconfigDataSet.ForumPostRow forumpostRow;
                id = (int)mpconfigDataSet.Tables["Posts"].Rows[postsBindingSource.Find("title", title)]["id"];
                if (id > 0)
                {
                    //add forums is alive
                    foreach (mpconfigDataSet.TemplatesRow r in mpconfigDataSet.Templates)
                    {
                        if (r["loginstatus"].ToString().Contains("Correct"))
                        {
                            forumpostRow = mpconfigDataSet.ForumPost.NewForumPostRow();
                            forumpostRow.forum_name = r.forum_name;
                            forumpostRow.id = id;
                            mpconfigDataSet.ForumPost.AddForumPostRow(forumpostRow);
                        }
                    }
                    forumPostTableAdapter.Update(mpconfigDataSet.ForumPost);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return id;
        }

        

        private void textBoxFilter_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (textBoxFilter.Text == "")
                    forumPostBindingSource.RemoveFilter();
                else
                {
                    string id = dataGridViewPosts.Rows[dataGridViewPosts.CurrentCell.RowIndex].Cells["idDataGridViewTextBoxColumnPost"].Value.ToString();
                    forumPostBindingSource.Filter = "id = " + id + " and (" + textBoxFilter.Text + ")";
                }
            }
               
        }


        private void dataGridViewPosts_CurrentCellChanged(object sender, EventArgs e)
        {
            if (dataGridViewPosts.CurrentCell != null)
            {
                string id = dataGridViewPosts.Rows[dataGridViewPosts.CurrentCell.RowIndex].Cells["idDataGridViewTextBoxColumnPost"].Value.ToString();
                //if (int.Parse(id) > 0)
                //{
                    if (_currentPost != int.Parse(id))
                    {
                        int index = forumPostBindingSource.Find("select_post", true);
                        if (index != -1)
                        {
                            MessageBox.Show("Posted Forums are not save yet!");
                            return; 
                        }
                        _currentPost = int.Parse(id);
                        string filter = "id = " + id;
                        if (textBoxFilter.Text != "")
                            filter += " and (" + textBoxFilter.Text + ")";
                        forumPostBindingSource.Filter = filter;
                    }
                //}
            }
        }

        public void AddNewForumPost(string id)
        {
            string sql = "select * from Templates where";
            sql += " content like 'App%'";
            sql += " and myposturl <> ''";
            sql += " and forum_name not in (select forum_name from ForumPost where id = " + id + ")";

            DataSet ds = MITI.BaseDBCe.ExecSql_DataSet(sql);
            //DataRow dr;
            mpconfigDataSet.ForumPostRow row;
            if (int.Parse(id) > 0)
            {
                //add forum is alive
                foreach (DataRow r in ds.Tables[0].Rows)
                {
                    row = mpconfigDataSet.ForumPost.NewForumPostRow();
                    row.id = int.Parse(id);
                    row.forum_name = r["forum_name"].ToString();
                    row.select_post = false;
                    //dr = mpconfigDataSet.Tables["ForumPost"].NewRow();
                    //dr["forum_name"] = r["forum_name"];
                    //dr["id"] = id;
                    //dr["select_post"] = false;
                    //mpconfigDataSet.ForumPost.Rows.Add(dr);
                    mpconfigDataSet.ForumPost.AddForumPostRow(row);
                }
                forumPostTableAdapter.Update(mpconfigDataSet.ForumPost);
                forumPostTableAdapter.Fill(mpconfigDataSet.ForumPost);
            }
        }

        private void btnUpdateForums_Click(object sender, EventArgs e)
        {
            try{
                if (dataGridViewPosts.CurrentCell != null)
                {
                    string id = dataGridViewPosts.Rows[dataGridViewPosts.CurrentCell.RowIndex].Cells["idDataGridViewTextBoxColumnPost"].Value.ToString();
                    AddNewForumPost(id);
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void dataGridViewPostedForums_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            try
            {
                int index = templatesBindingSource.Find("forum_name", dataGridViewPostedForums.Rows[e.RowIndex].Cells["forumnameDataGridViewTextBoxColumnPostForum"].Value.ToString());
                if (index >= 0)
                {
                    dataGridViewForums.FirstDisplayedScrollingRowIndex = index;
                    dataGridViewForums.Rows[index].Selected = true;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnCheckFoums_Click(object sender, EventArgs e)
        {
            //reset numbers of forums
            _selectedForums = 0;
            string url;
            DataRow templateRow;
            DataRow postForumRow;
            DataRow postRow;

            //Set biến để kiểm tra xem id có nằm trong url không
            foreach (DataGridViewRow dr in dataGridViewPostedForums.Rows)
            {
                //if (dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value != null)
                //{
                    if ((bool)dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value == true)
                    {
                        url = dr.Cells["forumnameDataGridViewTextBoxColumnPostForum"].Value.ToString();
                        if (!_urlList.Contains(url))
                        {
                            _selectedForums++;
                            //Use threads
                            HttpThread hp = new HttpThread();
                            templateRow = mpconfigDataSet.Tables["Templates"].Rows.Find(dr.Cells["forumnameDataGridViewTextBoxColumnPostForum"].Value.ToString());
                            postForumRow = mpconfigDataSet.Tables["ForumPost"].Rows.Find(new object[] { dr.Cells["forumnameDataGridViewTextBoxColumnPostForum"].Value.ToString(), dr.Cells["idDataGridViewTextBoxColumnPostForum"].Value.ToString() });
                            postRow = mpconfigDataSet.Tables["Posts"].Rows.Find(dr.Cells["idDataGridViewTextBoxColumnPostForum"].Value.ToString());
                            hp.startThread_FindPost(this, templateRow, postRow, postForumRow);
                        }
                    }
                //}
            }
        }

        private void btnUpdatePostForums_Click(object sender, EventArgs e)
        {
            //reset previous post
            _urlList.Clear();
            //uncheck forums of previous post
            foreach (DataGridViewRow dr in dataGridViewPostedForums.Rows)
            {
                if (dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value != null)
                    if ((bool)dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value == true)
                        dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value = false;
            }

            forumPostBindingSource.EndEdit();
            forumPostTableAdapter.Update(mpconfigDataSet.ForumPost);
            MessageBox.Show("Update successful!");
        }

        private void btnView_Click(object sender, EventArgs e)
        {
            richTextBoxSourceTest.Text = textBoxSourceTest.Text;
        }

        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void btnDefaultProfile_Click(object sender, EventArgs e)
        {
            DefaultProfile frm = new DefaultProfile();
            frm.ShowDialog();
        }

        private void comboBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            int index;
            int count = dataGridViewPostedForums.Rows.Count - 1;
            try
            {
                int group = comboBox2.SelectedIndex + 1;
                //reset previous post
                _urlList.Clear();

                //Reset group of forums that have group = comboBox2.SelectedIndex + 1
                foreach (DataGridViewRow dr in dataGridViewForums.Rows)
                {
                    if (dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value != null)
                    {
                        if ((bool)dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value == true)
                        {
                            if ((int)dr.Cells["groupDataGridViewTextBoxColumn"].Value == group)
                            {
                                if (group != 2)
                                    dr.Cells["groupDataGridViewTextBoxColumn"].Value = 2;
                                else
                                    dr.Cells["groupDataGridViewTextBoxColumn"].Value = 3;
                            }
                        }
                    }
                }

                //uncheck forums of previous post
                foreach (DataGridViewRow dr in dataGridViewPostedForums.Rows)
                {
                    if (dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value != null)
                        if ((bool)dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value == true)
                        {
                            dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value = false;
                            index = templatesBindingSource.Find("forum_name", dr.Cells["forumnameDataGridViewTextBoxColumnPostForum"].Value.ToString());
                            if (index >= 0)
                            {
                                dataGridViewForums.Rows[index].Cells["groupDataGridViewTextBoxColumn"].Value = group;
                            }
                        }
                }

                //Update data
                this.templatesBindingSource.EndEdit();
                this.templatesTableAdapter.Update(this.mpconfigDataSet.Templates);
                
                //Refresh
                int rowIndex = dataGridViewPostedForums.CurrentCell.RowIndex;
                int columnIndex = dataGridViewPostedForums.CurrentCell.ColumnIndex;
                this.forumPostTableAdapter.Fill(this.mpconfigDataSet.ForumPost);
                dataGridViewPosts_CurrentCellChanged(null, null);
                dataGridViewPostedForums.Rows[rowIndex].Cells[columnIndex].Selected = true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void btnDoPost_Click(object sender, EventArgs e)
        {

        }

        private void btnGetId_Click(object sender, EventArgs e)
        {
            //Add new F
            foreach (DataGridViewRow dr in dataGridViewForumThreads.Rows)
            {
                if (dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value != null)
                {
                    if ((bool)dr.Cells["selectDataGridViewCheckBoxColumnThread"].Value == true)
                    {
                        //foreach (DataGridViewRow r in dataGridViewIdThreads.Rows)
                        //{
                            HttpThread hp = new HttpThread();
                            hp.startThread_GetThreadIdByRegex(this, dr.Cells["urlDataGridViewTextBoxColumnThread"].Value.ToString(), mpconfigDataSet.Tables["Templates"].Rows.Find(dr.Cells["forumnameDataGridViewTextBoxColumnThread"].Value.ToString()));
                        //}
                    }
                }
            }
        }

        private void btnCheckAllPostForum_Click(object sender, EventArgs e)
        {
            if (btnCheckAllPostForum.Text == "Uncheck All")
            {
                foreach (DataGridViewRow dr in dataGridViewPostedForums.Rows)
                    dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value = (object)false;
                btnCheckAllPostForum.Text = "Check All";
            }
            else
            {
                foreach (DataGridViewRow dr in dataGridViewPostedForums.Rows)
                    dr.Cells["selectpostDataGridViewCheckBoxColumnPostForum"].Value = (object)true;
                btnCheckAllPostForum.Text = "Uncheck All";
            }
        }

        private void dataGridViewPosts_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (MessageBox.Show("Do you want to delete this post?", "Message", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.No)
                e.Cancel = true;
            else
            {
                string sql = "delete from ForumPost where id = " + e.Row.Cells["idDataGridViewTextBoxColumnPost"].Value.ToString();
                MITI.BaseDBCe.ExecSql_DataSet(sql);
                forumPostTableAdapter.Fill(mpconfigDataSet.ForumPost);
            }
        }

        private void dataGridViewPosts_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            postsBindingSource.EndEdit();
            postsTableAdapter.Update(mpconfigDataSet.Posts);
            MessageBox.Show("Delete Successful!");
        }

        private void comboBoxForums_SelectedIndexChanged(object sender, EventArgs e)
        {
            //1. View Forum Content
            //2. View Login Account
            //3. View Statistics Url
            //4. View Icons
            //5. View App Thread Ids
            //6. View Porn Thread Ids
            
            //foreach (DataGridViewRow dr in dataGridViewForums.Rows)
            //    dr.Cells["selectcheckforumDataGridViewCheckBoxColumn"].Value = (object)false;

            for (int i = 0; i < 4; i++)
                dataGridViewForums.Columns[i].Visible = true;

            int start, len;

            if (comboBoxForums.SelectedIndex == 0) //1. View Forum Content
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewForums.Columns.Count; i++)
                    dataGridViewForums.Columns[i].Visible = false;
                dataGridViewForums.Columns["forumtypeDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["languageDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["contentDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["currentmembersDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["currentguestsDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["threadsDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["postsDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["membersDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["messageDataGridViewTextBoxColumn"].Visible = true;
            }
            else if (comboBoxForums.SelectedIndex == 1)  //2. View Login Account
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewForums.Columns.Count; i++)
                    dataGridViewForums.Columns[i].Visible = false;
                dataGridViewForums.Columns["usernameDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["passwordDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["emailDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["forumtypeDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["languageDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["contentDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["loginstatusDataGridViewTextBoxColumn"].Visible = true;
            }
            else if (comboBoxForums.SelectedIndex == 2) //3. View Statistics Url
            {
                //Reset view columns
                for (int i = 4; i < dataGridViewForums.Columns.Count; i++)
                    dataGridViewForums.Columns[i].Visible = false;
                dataGridViewForums.Columns["usernameDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["myposturlDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["useridDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["languageDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["contentDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["posturlstatusDataGridViewTextBoxColumn"].Visible = true;
                dataGridViewForums.Columns["loginstatusDataGridViewTextBoxColumn"].Visible = true;
            }
            else if (comboBoxForums.SelectedIndex == 3) //4. View Icons
            {
                start = 6;
                len = 12;
                //Reset view columns
                for (int i = 4; i < dataGridViewForums.Columns.Count; i++){
                    if (i >= start && i < (start+ len))
                        dataGridViewForums.Columns[i].Visible = true;
                    else
                        dataGridViewForums.Columns[i].Visible = false;
                }
            }
            else if (comboBoxForums.SelectedIndex == 4) //5. View App Thread Ids
            {
                start = 18;
                len = 18;
                //Reset view columns
                for (int i = 4; i < dataGridViewForums.Columns.Count; i++)
                {
                    if (i >= start && i < (start + len))
                        dataGridViewForums.Columns[i].Visible = true;
                    else
                        dataGridViewForums.Columns[i].Visible = false;
                }
            }
            else if (comboBoxForums.SelectedIndex == 5) //6. View Porn Thread Ids
            {
                start = 36;
                len = 15;
                //Reset view columns
                for (int i = 4; i < dataGridViewForums.Columns.Count; i++)
                {
                    if (i >= start && i < (start + len))
                        dataGridViewForums.Columns[i].Visible = true;
                    else
                        dataGridViewForums.Columns[i].Visible = false;
                }
            }
        }

        private void btnPattern_Click(object sender, EventArgs e)
        {
            textBoxSearch.Text = @"url like '%%' and type like 'vBulletin' and language='English' and content like 'App%' and convert(current_guests,'System.Int32') > 0";
        }

        private void btnUpdatePost_Click(object sender, EventArgs e)
        {

        }

        private void dataGridViewPosts_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            Post frm = new Post(this, dataGridViewPosts.Rows[e.RowIndex]);
            frm.ShowDialog();
        }

        private void comboBoxPostedForum_SelectedIndexChanged(object sender, EventArgs e)
        {
            //1. View Forum Content
            //2. View Statistics Url
            //3. View App Thread Ids

            for (int i = 0; i < 3; i++)
                dataGridViewPostedForums.Columns[i].Visible = true;
            
            if (comboBoxPostedForum.SelectedIndex == 0) //1. View Forum Content
            {
                //Reset view columns
                for (int i = 3; i < dataGridViewPostedForums.Columns.Count; i++)
                    dataGridViewPostedForums.Columns[i].Visible = false;
                dataGridViewPostedForums.Columns["idDataGridViewTextBoxColumnPostForum"].Visible = false;

                dataGridViewPostedForums.Columns["typeDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["languageDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["contentDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["groupDataGridViewTextBoxColumnPostForum"].Visible = true;

                dataGridViewPostedForums.Columns["myposturlDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["poststatusDataGridViewTextBoxColumnPostForum"].Visible = true;
            }
            else if (comboBoxPostedForum.SelectedIndex == 1) //2. View Statistics Url
            {
                //Reset view columns
                for (int i = 3; i < dataGridViewPostedForums.Columns.Count; i++)
                    dataGridViewPostedForums.Columns[i].Visible = false;
                dataGridViewPostedForums.Columns["idDataGridViewTextBoxColumnPostForum"].Visible = false;
                //statistic
                dataGridViewPostedForums.Columns["currentmembersDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["currentguestsDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["threadsDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["postsDataGridViewTextBoxColumnPostForum"].Visible = true;
                dataGridViewPostedForums.Columns["membersDataGridViewTextBoxColumnPostForum"].Visible = true;
            }
            else if (comboBoxPostedForum.SelectedIndex == 2) //3. View App Thread Ids
            {
                int start, len;
                start = 14;
                len = 17;
                //Reset view columns
                for (int i = 3; i < dataGridViewPostedForums.Columns.Count; i++)
                {
                    if (i >= start && i < (start + len))
                        dataGridViewPostedForums.Columns[i].Visible = true;
                    else
                        dataGridViewPostedForums.Columns[i].Visible = false;
                }
                dataGridViewPostedForums.Columns["idDataGridViewTextBoxColumnPostForum"].Visible = false;
            }
        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (tabControl1.SelectedIndex == 0) //Check Forums
            {
                comboBoxSelectCommand.SelectedIndex = 0;
            }
            else if (tabControl1.SelectedIndex == 1) //Forum Threads
            {
                if (this.threadTemplatesTableAdapter.Connection.ConnectionString != GeneralClass.ConnectString())
                {
                    // TODO: This line of code loads data into the 'mpconfigDataSet.ThreadTemplates' table. You can move, or remove it, as needed.
                    this.threadTemplatesTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
                    this.threadTemplatesTableAdapter.Fill(this.mpconfigDataSet.ThreadTemplates);

                    // TODO: This line of code loads data into the 'mpconfigDataSet.Threads' table. You can move, or remove it, as needed.
                    this.threadsTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
                    this.threadsTableAdapter.Fill(this.mpconfigDataSet.Threads);
                    threadsBindingSource.Filter = "Visible = true";

                    // TODO: This line of code loads data into the 'mpconfigDataSet.ThreadKeywords' table. You can move, or remove it, as needed.
                    this.threadKeywordsTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
                    this.threadKeywordsTableAdapter.Fill(this.mpconfigDataSet.ThreadKeywords);
                }
            }
            else if (tabControl1.SelectedIndex == 2)
            {
                if (this.postsTableAdapter.Connection.ConnectionString != GeneralClass.ConnectString())
                {
                    // TODO: This line of code loads data into the 'mpconfigDataSet.Posts' table. You can move, or remove it, as needed.
                    this.postsTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
                    this.postsTableAdapter.Fill(this.mpconfigDataSet.Posts);

                    // TODO: This line of code loads data into the 'mpconfigDataSet.ForumPost' table. You can move, or remove it, as needed.
                    this.forumPostTableAdapter.Connection.ConnectionString = GeneralClass.ConnectString();
                    this.forumPostTableAdapter.Fill(this.mpconfigDataSet.ForumPost);
                }
                comboBoxPostedForum.SelectedIndex = 0;
            }
            else if (tabControl1.SelectedIndex == 3)
            {
                
            }
        }

        private void btnKeyWord_Click(object sender, EventArgs e)
        {

        }
    }
}
